<template>
    <div class="user_info">
        <div class="base_header">
            <img @click="goBack()" class="back" src="../../assets/img/back.png" alt="">个人资料
        </div>
        <div class="item_info border1" > <!-- @click="showActionSheet()" -->
            <span class="s1">头像</span>
            <span class="s2">
                <img  v-if='imgurl==""&&(person.headImg==""||person.headImg==null)' class="head_img" src="../../assets/img/user/test-head.png" alt="">
                <img v-else-if='imgurl==""&&person.headImg' :src="imgDomin+person.headImg" alt=""  class="head_img" >
                <img v-else :src="imgurl" alt=""  class="head_img" >
            </span>
            <img src="../../assets/img/goods/arrow.png" alt="">
        </div>
        <div class="item_info border1">
            <span class="s1">昵称</span>
            <span class="s2"><input type="text" v-model="person.nickName"></span>
            <img src="../../assets/img/goods/arrow.png" alt="">
        </div>
        <div class="item_info border1" @click="popSex">
            <span class="s1">性别</span>
            <span class="s2" v-if="person.gender == 1">男</span>
            <span class="s2" v-if="person.gender == 0">女</span>
            <img src="../../assets/img/goods/arrow.png" alt="" class="fr">
        </div>
        <div class="item_info mb10" id="showDateP2">
            <span class="s1">生日</span>
            <span class="s2" id="showDate">{{person.birthday}}</span>
            <img src="../../assets/img/goods/arrow.png" alt="">
        </div>
        <div class="item_info border1">
            <span class="s1">手机号</span>
            <span class="s2">{{person.mobile}}</span>
            <img src="../../assets/img/goods/arrow.png" alt="">
        </div>
        <div class="item_info border1" id="select_contact">
            <span class="s1">所在地</span>
            <span class="s2" data-province-code="" data-city-code="" data-district-code=""
                  id="show-contact">{{person.provinceName}}{{person.cityName}}{{person.regionName}}</span>
            <img src="../../assets/img/goods/arrow.png" alt="">
        </div>
        <router-link :to="{path:'/set_local'}">
            <div class="item_info mb10">
                <span class="s1">收货地址</span>
                <span class="s2"></span>
                <img src="../../assets/img/goods/arrow.png" alt="">
            </div>
        </router-link>
        <mt-popup v-model="selectSex" position="bottom" style="width: 90%;margin: auto;background: none">
            <ul class="select_sex vertical-list">
                <li :class="{'active':userSex == 1}" @click="selectUserSex(1)">男</li>
                <li :class="{'active':userSex == 0}" @click="selectUserSex(0)">女</li>
                <li class="bt" @click="saveSex()">保存</li>
            </ul>
        </mt-popup>
        <div class="bts" @click="savePerson()">保存</div>
    </div>
</template>

<style>
    @import url("./user-info.css");
    @import url("../../../static/js/iosSelect.css");
</style>
<script>
    import Layer from '../../assets/js/MessageBox'
    import API from '../../assets/js/API'
    import Validate from '../../assets/js/Validate'

    export default {
        data() {
            return {
                selectSex: false,
                userSex: 0,
                person: {},
                personRequest: {
                    address: "",
                    cityId: "",
                    gender: "",
                    headImg: "",
                    mobile: "",
                    nickName: "",
                    provinceId: "",
                    regionId: "",
                    birthday: ""
                },
               imgurl:'',
               imgDomin:API.testQiNiuUrl
            }
        },
        created() {
             window.scrollTo(0,0);
            let url = API.serviceDomain + API.personDetail;
            this.$http.get(url).then(
                (res) => {
                    if (res.body.status == '000000') {
                        this.person = res.body.data.userInfo;
                        this.personRequest.regionId = this.person.regionId;
                        this.personRequest.provinceId = this.person.provinceId;
                        this.personRequest.cityId = this.person.cityId;
                        this.userSex = this.person.gender;
                        this.personRequest.headImg=this.person.headImg
                    } else {
                        Layer.showMsg(res.body.message);
                    }
                },
                (error) => {
                    Layer.showMsg("服务器开小差了...")
                    return
                }
            )
        },
        mounted() {
            // 选择生日iosSelect初始化
            let showDateDom = $('#showDate');
            let showDateP2 = $('#showDateP2');

            let now = new Date();
            let nowYear = now.getFullYear();
            let nowMonth = now.getMonth() + 1;
            let nowDate = now.getDate();
            showDateDom.attr('data-year', nowYear);
            showDateDom.attr('data-month', nowMonth);
            showDateDom.attr('data-date', nowDate);
            let _this = this;
            let that = this
            showDateP2.bind('click', function () {
                let oneLevelId = showDateDom.attr('data-year');
                let twoLevelId = showDateDom.attr('data-month');
                let threeLevelId = showDateDom.attr('data-date');
                let iosSelect = new IosSelect(3,
                    [that.yearData, that.monthData, that.dateData],
                    {
                        title: '出生日期选择',
                        itemHeight: 35,
                        relation: [1, 1],
                        oneLevelId: oneLevelId,
                        twoLevelId: twoLevelId,
                        threeLevelId: threeLevelId,
                        showLoading: true,
                        callback: function (selectOneObj, selectTwoObj, selectThreeObj) {
                            showDateDom.attr('data-year', selectOneObj.id);
                            showDateDom.attr('data-month', selectTwoObj.id);
                            showDateDom.attr('data-date', selectThreeObj.id);
                            _this.person.birthday = selectOneObj.value + '-' + selectTwoObj.value + '-' + selectThreeObj.value
                        }
                    });
                let a = $('.sure');
                a[0].onclick = function () {
                    that.birthday = showDateDom.text()
                }
            });
            // 选择地址初始化
            let selectContactDom = $('#select_contact');
            let showContactDom = $('#show-contact');
            selectContactDom.bind('click', function () {
                let sccode = showContactDom.attr('data-city-code');
                let scname = showContactDom.attr('data-city-name');
                let oneLevelId = showContactDom.attr('data-province-code');
                let twoLevelId = showContactDom.attr('data-city-code');
                let threeLevelId = showContactDom.attr('data-district-code');
                let iosSelect = new IosSelect(3,
                    [iosProvinces, iosCitys, iosCountys],
                    {
                        title: '地址选择',
                        itemHeight: 35,
                        relation: [1, 1, 0, 0],
                        oneLevelId: oneLevelId,
                        twoLevelId: twoLevelId,
                        threeLevelId: threeLevelId,
                        callback: function (selectOneObj, selectTwoObj, selectThreeObj) {
                            _this.person.provinceName = selectOneObj.value;
                            _this.person.cityName = selectTwoObj.value;
                            _this.person.regionName = selectThreeObj.value;
                            _this.personRequest.cityId = selectTwoObj.id;
                            _this.personRequest.provinceId = selectOneObj.id;
                            _this.personRequest.regionId = selectThreeObj.id;
                        }
                    });
            });
        },
        methods: {
            goBack() {
                this.$router.goBack()
            },
            formatYear: function (nowYear) {
                let arr = [];
                for (let i = nowYear - 117; i <= nowYear; i++) {
                    arr.push({
                        id: i + '',
                        value: i
                    });
                }
                return arr;
            },
            formatMonth: function () {
                let arr = [];
                for (let i = 1; i <= 12; i++) {
                    if (i <= 9) {
                        arr.push({
                            id: i + '',
                            value: '0' + i
                        });
                    } else {
                        arr.push({
                            id: i + '',
                            value: i
                        });
                    }
                }
                return arr;
            },
            formatDate: function (count) {
                let arr = [];
                for (let i = 1; i <= count; i++) {
                    if (i <= 9) {
                        arr.push({
                            id: i + '',
                            value: '0' + i
                        });
                    } else {
                        arr.push({
                            id: i + '',
                            value: i
                        });
                    }
                }
                return arr;
            },
            yearData: function (callback) {
                let that = this
                let now = new Date();
                let nowYear = now.getFullYear();
                callback(that.formatYear(nowYear))
            },
            monthData: function (year, callback) {
                let that = this
                callback(that.formatMonth());
            },
            dateData: function (year, month, callback) {
                let that = this
                if (/^[13578]$|^1[02]$/.test(month)) {
                    callback(that.formatDate(31));
                }
                else if (/^[469]$|^11$/.test(month)) {
                    callback(that.formatDate(30));
                }
                else if (/^2$/.test(month)) {
                    if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
                        callback(that.formatDate(29));
                    }
                    else {
                        callback(that.formatDate(28));
                    }
                }
                else {
                    throw new Error('month is illegal');
                }
            },
            popSex() {
                this.selectSex = true
            },
            saveSex() {
                this.selectSex = false
                this.person.gender = this.userSex;
            },
            selectUserSex(sex) {
                this.userSex = sex
            },
            savePerson() {
                this.personRequest.address = this.person.address;
                this.personRequest.gender = this.person.gender;
                this.personRequest.headImg = this.person.headImg;//
                this.personRequest.mobile = this.person.mobile;
                this.personRequest.nickName = this.person.nickName;
                this.personRequest.birthday = this.person.birthday;
                let url = API.serviceDomain + API.personModify;
                console.log(this.personRequest.headImg)
                this.$http.post(url, this.personRequest).then(
                    (res) => {
                        if (res.body.status == '000000') {
                            Layer.showMsg("修改成功")
                        } else {
                            Layer.showMsg(res.body.message);
                        }
                    },
                    (error) => {
                        Layer.showMsg("服务器开小差了...")
                        return
                    }
                )
            },
            getToken(url){
                    let form=new FormData()
                    this.$http.get(API.testQiNiuUrl+API.ybAvatarBucket,{
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                    })
                    .then(
                        (res)=>{
                            this.token=res.body.retMsg
                            this.uploadImg(res.body.retMsg,url)
                        }
                        )
            },
            uploadImg(token,new_file){
                let that=this
                let wt = plus.nativeUI.showWaiting();  
                let task = plus.uploader.createUpload("http://upload.qiniu.com", {
                    method: "POST"
            }, function(t, status) { //
                        let data = JSON.parse(t.responseText);
                        if (status == 200) {
                            alert(3)
                            console.log(3)
                            that.person.headImg=data.hash;
                            console.log(that.person.headImg)
                            wt.close();
                        } else {
                            mui.toast("上传失败：" + status);
                            wt.close();
                        }
                    })
                    task.addFile(new_file, { key: "file" });
                    task.addData("token", token);//七牛所需参数
                    task.start();
            },
            showActionSheet() {   
                let that=this;
                    let bts = [{    
                        title: "拍照"    
                    }, {    
                        title: "从相册选择"    
                    }];    
                    plus.nativeUI.actionSheet({    
                            cancel: "取消",    
                            buttons: bts    
                        },    
                        function(e) {    
                            if (e.index == 1) {    
                                that.getImage();    
                            } else if (e.index == 2) {    
                                that.galleryImgs();    
                            }    
                        }    
                    );    
                },  
                //从相册选择照片  
            galleryImgs() {
                let that=this;
                    plus.gallery.pick(function(e) {    
                        let name = e.substr(e.lastIndexOf('/') + 1);  
                    that.compressImage(e,name);  
                    }, function(e) {    
                    }, {    
                        filter: "image"    
                    });    
                },
                //拍照
                getImage() {  
                    let that=this
                let cmr = plus.camera.getCamera();    
                cmr.captureImage(function(p) {    
                    plus.io.resolveLocalFileSystemURL(p, function(entry) {    
                        that.compressImage(entry.toLocalURL(),entry.name);    
                    }, function(e) {    
                        plus.nativeUI.toast("读取拍照文件错误：" + e.message);    
                    });    
                }, function(e) {    
                }, {    
                    filter: 'image'   
                });    
            },  
                //压缩图片    
            compressImage(url,filename){  
                    let that=this;
                let name="_doc/upload/"+filename;  
                plus.zip.compressImage({    
                        src:url,//src: (String 类型 )压缩转换原始图片的路径    
                        dst:name,//压缩转换目标图片的路径    
                        quality:40,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100    
                        overwrite:true//overwrite: (Boolean 类型 )覆盖生成新文件    
                    },    
                    function(zip) {  
                        //页面显示图片  
                        console.log(zip.target)
                        that.showPics(zip.target,name);  
                    },function(error) {    
                        plus.nativeUI.toast("压缩图片失败，请稍候再试");    
                });    
            },
            showPics(url,name){          
                //根据路径读取到文件   
                let that=this
                plus.io.resolveLocalFileSystemURL(url,function(entry){  
                    entry.file( function(file){  
                        let fileReader = new plus.io.FileReader();  
                        fileReader.readAsDataURL(file);  
                        fileReader.onloadend = function(e) {  
                                let picUrl= e.target.result.toString(); 
                                that.getToken(url )
                                that.imgurl=picUrl
                        }  
                    });  
                });   
            }  
        }

    }
</script>
